package meiyunting.shiwuzhaoling.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.nio.file.Paths;

/**
 * 文件上传和访问控制器
 */
@Controller
@RequestMapping("/uploads")
public class UploadController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    /**
     * 直接提供图片文件访问
     */
    @GetMapping("/images/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveImage(@PathVariable String filename) {
        try {
            // 获取上传目录的绝对路径
            File uploadDirFile = new File(uploadDir);
            if (!uploadDirFile.isAbsolute()) {
                uploadDirFile = new File(System.getProperty("user.dir"), uploadDir);
            }
            
            // 构建文件路径
            File file = Paths.get(uploadDirFile.getAbsolutePath(), filename).toFile();
            
            // 输出调试信息
            System.out.println("【图片访问】请求文件: " + filename);
            System.out.println("【图片访问】完整路径: " + file.getAbsolutePath());
            System.out.println("【图片访问】文件存在: " + file.exists());
            
            if (!file.exists()) {
                System.err.println("【警告】请求的文件不存在: " + file.getAbsolutePath());
                return ResponseEntity.notFound().build();
            }
            
            // 创建文件资源
            Resource resource = new FileSystemResource(file);
            
            // 确定内容类型
            String contentType = determineContentType(filename);
            
            // 返回文件资源
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                    .body(resource);
        } catch (Exception e) {
            System.err.println("【错误】图片访问异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 根据文件名确定内容类型
     */
    private String determineContentType(String filename) {
        if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (filename.endsWith(".png")) {
            return "image/png";
        } else if (filename.endsWith(".gif")) {
            return "image/gif";
        } else if (filename.endsWith(".jfif")) {
            return "image/jpeg";
        } else {
            return "application/octet-stream";
        }
    }
} 